package com.social.servlet;

import com.social.dao.LogDao;
import com.social.dao.UserDAO;
import com.social.model.Comment;
import com.social.model.Log;
import com.social.model.Reply;
import com.social.model.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CommentShowServlet", value = "/CommentShowServlet")
public class CommentShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html; charset=UTF-8");

        PrintWriter out = response.getWriter();

        int logId = Integer.parseInt(request.getParameter("logId"));



        UserDAO userDAO = new UserDAO();

        LogDao l = new LogDao();

        Log log = new Log();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");


        //默认值为3，也就是每页最多三个评论
        int pageSize = 3;

        int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
        int total = l.commentCount(logId);

        int totalPages = (int) Math.ceil((double) total / pageSize);





        log = l.getUserIDContentAndImg(logId);
//        System.out.println(log.getUserId());
        User author = userDAO.getUserByNickname(log.getUserId());




try{
        StringBuilder logHtml = new StringBuilder();

        logHtml.append("<div class=\"log-card\">")
                .append("<div class=\"log-header\">")
                .append("<img src=\"").append(author.getAvatar()).append("\" alt=\"用户头像\" class=\"log-avatar\">")
                .append("<span class=\"log-author\">").append(author.getNickname()).append("</span>")
                .append("<span class=\"log-time\">").append(sdf.format(log.getCreateTime())).append("</span>");

        logHtml.append("</div>").append("<div class=\"log-content\">").append(log.getContent()).append("</div>");

        // 处理图片（微信朋友圈风格布局）
        String[] images = log.getImgAdreess();
        if (images != null) {
            logHtml.append("<div class=\"log-images\">");
            for (String img : images) {
                if (img != null && !img.trim().isEmpty()) {
                    logHtml.append("<div class=\"image-container\">");
                    logHtml.append("<img src=\"").append(img).append("\" class=\"log-image\">")
                            .append("</div>");
                }
            }
            logHtml.append("</div>");
        }

        logHtml.append(
                "    <div>\n" +
                "        <textarea id=\"content\" name=\"content\" rows=\"5\" placeholder=\"请输入内容...\"></textarea>\n" +
                "         <button type=\"submit\" class = \"launch\" ").append(">发送</button></div>");


    List<Comment> comments = new ArrayList<>();
    comments = l.getNickname_Avatar(logId,page,pageSize);

    if(comments!=null){
    for(Comment a : comments){
        logHtml.append("<div class=\"comment-item\"><img src=\"").append(a.getAvatar())
                .append("\"class='comment-avatar'><div class=\"comment-info\"><span class=\"comment-nickname\">")
                .append(a.getNickname()).append("</span><p class=\"comment-content\">").append(a.getContent())

                .append("</p> ");
//                =================================================
//                lwz
//                在p标签后面添加回复内容
//                回复列表容器
        List<Reply> replies = new ArrayList<>();
        replies = l.returnReply(a.getC_id());
        if(replies!=null){
            for(Reply r : replies){
                logHtml.append("    <div class=\"reply-list\" >")
                        .append("<img src=\"")
                        .append(r.getAvatar())
                        .append("\"class=\"reply-avatar\">")
                        .append("<div><span class=\"reply-nickname\">")
                        .append(r.getNickname())
                        .append(" </span><span class=\"reply-content\">")
                        .append(r.getR_content())
                        .append("</span></div></div>");

            }

        }




//                ==================================================================================================
//                lwz
                //                在回复内容后面标签后添加的回复按钮
//==============================================================================
//                在发送按钮里面插入c_id,也就是评论id，这样我们就知道回复到底是给哪条评论进行回复的
               logHtml .append("<button class=\"reply-btn\" onclick=\"toggleReplyBox(this)\">回复</button>\n" +
                "    <div class=\"reply-box\" style=\"display: none;\">\n" +
                "      <textarea class=\"reply-textarea\" placeholder=\"回复内容...\"></textarea>\n" +
                "      <button class=\"reply-send-btn\" onclick=\"sendReply(this)\"").append("data-comment-id=\"")
                .append(a.getC_id()).append("\">发送</button></div></div></div>");
    }
}



//    这是log-card的div标签
//        我把它挪到了最下面，而且是用paginationHtml加的


    //=============================================================================
//===============================================================================
    //lwz copy shikaiqi
//    分页按钮


    // 构建分页HTML
    StringBuilder paginationHtml = new StringBuilder("<div class='pagination'>");
    // 上一页
    if (page > 1) {
        paginationHtml.append("<a href='javascript:void(0)' onclick='loadLogs(")
                .append(logId).append(",") .append(page - 1).append(")'>上一页</a>");
    }
    // 页码
    for (int i = 1; i <= totalPages; i++) {
        String activeClass = (i == page) ? "active" : "";
        paginationHtml.append("<a href='javascript:void(0)' class='").append(activeClass).append("' onclick='loadLogs(")
                .append(logId).append(",").append(i).append(")'>").append(i).append("</a>");
    }
    // 下一页
    if (page < totalPages) {
        paginationHtml.append("<a href='javascript:void(0)' onclick='loadLogs(")
                .append(logId).append(",").append(page + 1).append(")'>下一页</a>");
    }
    paginationHtml.append("</div>");




    paginationHtml.append("</div>");


    out.print(logHtml.toString() + paginationHtml.toString());

    } finally {
        out.close();
    }



    }


}
